package com.suyl.candy.weather.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 根据请求获取ip地址
 */
public class IpUtils {
    private IpUtils() {
    }

    /**
     * 获取ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取ip地址
     * 如果是本机ip,根据网卡获取本机ip地址
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String loginIp = getIpAddr(request);
        if ("127.0.0.1".equals(loginIp) || "0:0:0:0:0:0:0:1".equals(loginIp)) {
            // 根据网卡取本机Ip
            InetAddress inetAddress = null;
            try {
                inetAddress = InetAddress.getLocalHost();
                loginIp = inetAddress.getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        return loginIp;
    }
}